package com.ldgk.pim.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.ldgk.pim.client.rpc.VisitService;
import com.ldgk.pim.data.Visit;

@SuppressWarnings("serial")
/**
 * VisitService server-side implementation
 */
public class VisitServiceImpl extends RemoteServiceServlet implements VisitService {

	/**
	 * {@inheritDoc}
	 */	
	public List<Visit> findByPlace(long placeKey){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

		Query q = new Query("Visit");
		q.addFilter("placeKey", Query.FilterOperator.EQUAL, placeKey);
		
		PreparedQuery pq = ds.prepare(q);
		
		ArrayList<Visit> lista = new ArrayList<Visit>();
		for(Entity entity: pq.asIterable())
			lista.add(entityToVisit(entity));

		return lista;
	}
	
	/**
	 * {@inheritDoc}
	 */	
	public void persist(Visit v){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		Entity e = visitToEntity(v);
		ds.put(e);
	}
	
	/**
	 * {@inheritDoc}
	 */	
	public void delete(Visit visit){
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		Key key = KeyFactory.createKey("Visit",visit.getKey());
		ds.delete(key);
	}
	
	/**
	 * Converts a datastore entity into a Visit object
	 * @param e - datastore entity
	 * @return Visit object
	 */
	private Visit entityToVisit(Entity e){
		Visit v = new Visit();
		v.setKey(e.getKey().getId());
		v.setPlaceKey((Long)e.getProperty("placeKey"));
		v.setDate((Date)e.getProperty("date"));
		v.setWhite((int)((Long)e.getProperty("white")).longValue());
		v.setGray((int)((Long)e.getProperty("gray")).longValue());
		v.setBlue((int)((Long)e.getProperty("blue")).longValue());
		return v;
	}
	
	/**
	 * Convers a Visit object into a datastore entity
	 * @param v - Visit object
	 * @return - datastore entity
	 */
	private Entity visitToEntity(Visit v){
		Entity e = null;
		if( v.getKey() != -1 ){
			e = new Entity(KeyFactory.createKey("Visit", v.getKey()));
		}else{
			e = new Entity("Visit");
		}
		
		e.setProperty("placeKey",v.getPlaceKey());
		e.setProperty("date",v.getDate());
		e.setProperty("white",v.getWhite());
		e.setProperty("gray",v.getGray());
		e.setProperty("blue",v.getBlue());
		
		return e;
	}
}
